var Trees = require('./libs/jurisdictions');


var mslibrary = require("ms-common-library");

module.exports = function (UC, source, config, ArFor, cache, package) {
    var UserControl = UC;
    var Jurisdictions = Trees(config);
    var router = function (req, res, next) {
        var ajaxTest = {
            error: 0
        };
        var Request = req.body;

        var ajaxTest = {
            error: 0
        };
        if (UserControl.getoff(req.session.key)) {
            Request = UserControl.GetForm(req.session.key, Request);
  

            new source("M_1", Request, function (db) {
                if (db) {
                    
                    var socket_id = UserControl.GetParamet(req.session.key, 'socket_id');

                    var token = mslibrary.MD5(db.filename + '/' + db.id + "/" + config.id + "/" + config.version+ "/" + package.version);
                    req.token.set(token);
                    var etag_key = 'W/ms-' + token;
                    if (etag_key == req.getHeader('if-none-match')) {
                        req.notModified()
                        return
                    } else {
                        res.etag_key = etag_key;
                    }
                    Jurisdictions(db, function (_db) {
                        _db.socket_id = socket_id;
                        _db.token = token;
                        res.Json(_db);
                    });

                } else {
                    ajaxTest.error = 1;
                    res.Json(ajaxTest);
                }

            });
        } else {
            ajaxTest.error = 1;
            var LoadingDate = req.session.LoadingDate;
            if (LoadingDate && (new Date() - new Date(LoadingDate)) / 1000 < (req.session.LoginErrorlen - 3) * 5 * 60) {
                ajaxTest.error = 1001;
                ajaxTest.LoadingDate = parseInt(Math.abs((new Date() - new Date(LoadingDate)) / 1000 - ((req.session.LoginErrorlen - 3) * 5 * 60)));
            }
            res.Json(ajaxTest);
        }

    }
    return router;

}